package docview;

import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.tree.DefaultMutableTreeNode;
import tableprocessor.CathegoryStaticTreeFactory;
import tableprocessor.ColumnPare;
import tableprocessor.DBCathegory;
import tableprocessor.DBColumn;
import tableprocessor.DBProduceDAO;
import tableprocessor.Pare;
/**
 *
 * @author gleb
 */
public class ResultDocManager implements MouseListener,CathegoryEventListener,Runnable,DeleteActionListener
{
    private DocTable table;
    private DefaultMutableTreeNode last;
    private PriceSessionStore storage;
    private JFrame saveFrame;
    private JTextArea log;
    private JProgressBar progressBar;
    private ViewNewDoc newdoc;
    ResultDocManager(DocTable _table,PriceSessionStore _storage, ViewNewDoc _newdoc)
    {
        table = _table;
        storage = _storage;
        newdoc = _newdoc;
    }
    public void mouseClicked(MouseEvent e)
    {
         if (JOptionPane.showConfirmDialog(null, "Загрузить в базу ?")==0)
         {
             Thread thread = new Thread(this);
             thread.start();
         }
    }
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}

    public void selectCathegoryEvent(DefaultMutableTreeNode node)
    {
        if (CathegoryStaticTreeFactory.getPriceDAO().isHasColumns(node))
        {
            if (last!=null)
            {
               // if (!last.equals(node))
                {

                    if (storage != null)
                    {
                        boolean isAdd = false;
                        int colCount = table.getColorTable().getColumnCount();
                        int rowCount = table.getColorTable().getRowCount();
                        for (int i = 0 ; i < rowCount; i++)
                        {
                            for (int k = 0 ; k < colCount; k++)
                            {
                                if (table.getColorTable().getValueAt(i, k)!=null && !table.getColorTable().getValueAt(i, k).toString().isEmpty())
                                {
                                    isAdd = true;
                                }
                            }
                            if (isAdd)
                            {
                                for (int j = 0 ; j < colCount; j++)
                                {
                                    Object o = table.getColorTable().getValueAt(i, j);
                                    if (o==null)
                                    {
                                        storage.add("",table.getColorTable().getColumnName(j),i,j,last);
                                    }
                                    else
                                    {
                                        String val = o.toString();
                                        if (val.isEmpty()||val.equals(""))
                                        {

                                            storage.add("",table.getColorTable().getColumnName(j),i,j,last);
                                        }
                                        else
                                        {
                                             storage.add(val,table.getColorTable().getColumnName(j),i,j,last);
                                        }
                                    }
                                    //if (table.getColorTable().getValueAt(i, j)!=null)
                                    //storage.add(table.getColorTable().getValueAt(i, j).toString(),
                                    //table.getColorTable().getColumnName(j),i,j, last);
                                }
                                isAdd = false;
                            }
                        }
                    }
                }
            }
            last = node;
        }
    }

    public void run()
    {
        saveFrame = new JFrame();
        saveFrame.setTitle("Загрузка, подождите...");
        saveFrame.setBounds(200, 200, 400, 100);
        saveFrame.setLayout(new GridLayout(2,1));
        progressBar = new JProgressBar();
        progressBar.setValue(0);
        progressBar.setStringPainted(true);
        log = new JTextArea();
        log.setEditable(false);
        log.setFont(new Font(Font.SANS_SERIF,Font.ITALIC,12));
        JScrollPane spane = new JScrollPane(log);
        saveFrame.add(progressBar);
        saveFrame.add(spane);
        saveFrame.setVisible(true);
        selectCathegoryEvent(last);
        log.append("Очистка базы...\n");
        Iterator<DefaultMutableTreeNode> c_iter = newdoc.getVisitedCathegories();
        while (c_iter.hasNext())
        {
            CathegoryStaticTreeFactory.getPriceDAO().clearProduceTableByCathegory(c_iter.next());
        }
        //log.append("Начало загрузки....\n");
        log.append("Формировка списка категорий....\n");
        log.append("Загрузка категориий....\n");
        Iterator<DefaultMutableTreeNode> catit = storage.getCathegories();
        while (catit.hasNext())
        {
            DefaultMutableTreeNode node = catit.next();
            log.append("Загрузка категории....\n");
            log.append(CathegoryStaticTreeFactory.getPriceDAO().findByNode(node).getDbcat().getName()+"\n");
            saveByCathegory(node);
        }
        progressBar.setValue(100);
        saveFrame.setVisible(false);
        Thread.yield();
    }
    private void saveByCathegory(DefaultMutableTreeNode node)
    {
        Pare p = CathegoryStaticTreeFactory.getPriceDAO().findByNode(node);
        Iterator<ColumnPare> cpare = CathegoryStaticTreeFactory.getPriceDAO().getColumnsForCathegory(node);
        int row = storage.getRowCountForCathegory(node)+1;
        int col = storage.getColCountForCathegory(node)+1;
        for (int i = 0 ; i < row; i++)
        {
            for (int j = 0 ; j < col; j++)
            {
                log.append("Загрузка строки "+i+"\n");
                PriceSessionStoreObject obj = storage.getByPosition(i, j, node);
                if (obj != null)
                {
                    log.append(getColumnByNameAndCathegory(obj.getColName(),obj.getNode()).getName());
                    log.append(" "+obj.getValue()+"\n");
                    DBProduceDAO.addProduce(obj.getValue(),
                    p.getDbcat().getId(),getColumnByNameAndCathegory(obj.getColName(),obj.getNode()).getId(),i+1);
                }
            }
        }
    }
    private DBColumn getColumnByNameAndCathegory(String name,DefaultMutableTreeNode node)
    {
        Iterator<ColumnPare> cpare = CathegoryStaticTreeFactory.getPriceDAO().getColumnsForCathegory(node);
        while (cpare.hasNext())
        {
            DBColumn col = cpare.next().getDbcol();
            if(col.getName().equals(name))
            {
                return col;
            }
        }
        return null;
    }

    public void deleteCell(int row, int col, DefaultMutableTreeNode node)
    {
        if (node==null)
        {
            storage.removeByColumnAndRow(last, row, col);
        }
        else
        {
            storage.removeByColumnAndRow(node, row, col);
        }
    }
    public void deleteRow(int row, DefaultMutableTreeNode node)
    {
        if (node==null)
        {
            storage.removeByRow(last, row);
        }
        else
        {
            storage.removeByRow(node, row);
        }
    }

}
